package com.sleep.springbootdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sleep.springbootdemo.dao.DemoMapper;
import com.sleep.springbootdemo.param.LoginParam;
import com.sleep.springbootdemo.pojo.Demo;
import com.sleep.springbootdemo.service.DemoService;
import com.sleep.springbootdemo.vo.ResultCode;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 继承 DemoService，使用 @Service 注解将该类标识为 service 层的类，并注入 spring 容器
 * 创建 dao 层的 mapper 接口，实现对数据库中的表的操作
 *
 * @author Sleep-6000
 * @date 2022/8/5
 */
@Service
public class DemoServiceImpl implements DemoService {

    /**
     * 加密盐
     */
    private static final String SLAT = "sleep-6000+-*/";

    @Autowired
    private DemoMapper demoMapper;

    /**
     * 实现 DemoService 中的登录方法
     *
     * @param loginParam 登录参数
     * @return 结果
     */
    @Override
    public int login(LoginParam loginParam) {
        String username = loginParam.getUsername();
        String pwd = loginParam.getPwd();
        if (StringUtils.isBlank(username) || StringUtils.isBlank(pwd)) {
            return ResultCode.PARAMS_ERROR.getCode();
        }
        // 对密码进行 md5 加密
        String newPwd = DigestUtils.md5Hex(pwd + SLAT);

        // 查询数据库中是否存在
        LambdaQueryWrapper<Demo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Demo::getUsername, username);
        wrapper.eq(Demo::getPwd, newPwd);
        Demo demo = demoMapper.selectOne(wrapper);
        if (demo == null) {
            return ResultCode.ACCOUNT_PWD_NOT_EXIST.getCode();
        }

        return ResultCode.SUCCESS.getCode();
    }

    /**
     * 实现 DemoService 中的注册方法
     *
     * @param loginParam 注册参数
     * @return 结果
     */
    @Override
    public int register(LoginParam loginParam) {
        String username = loginParam.getUsername();
        String pwd = loginParam.getPwd();
        if (StringUtils.isBlank(username) || StringUtils.isBlank(pwd)) {
            return ResultCode.PARAMS_ERROR.getCode();
        }
        // 对密码进行 md5 加密
        String newPwd = DigestUtils.md5Hex(pwd + SLAT);

        Demo demo = new Demo();
        demo.setUsername(username);
        demo.setPwd(newPwd);
        demoMapper.insert(demo);
        return ResultCode.SUCCESS.getCode();
    }

    @Override
    public int getNum() {
        return demoMapper.getNum();
    }
}
